<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Spatie\EloquentSortable\Sortable;
use Spatie\EloquentSortable\SortableTrait;

/**
 * @property int $id
 * @property string $name
 * @property int $user_count
 * @property int $test_count
 * @property int $full_count
 * @property float $average_score
 * @property int $order
 */
class Unit extends Model implements Sortable
{
    use SortableTrait;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
    ];

    /**
     * 排序
     *
     * @var array
     */
    protected $sortable = [
        // 设置排序字段名称
        'order_column_name' => 'order',
        // 是否在创建时自动排序，此参数建议设置为true
        'sort_when_creating' => true,
    ];

    /**
     * 统计各单位用户数
     */
    public static function refreshUserCount()
    {
        User::query()
            ->selectRaw('unit_id, COUNT(*) as count')
            ->groupBy('unit_id')
            ->pluck('count', 'unit_id')
            ->map(function ($count, $id) {
                static::query()->where('id', $id)->update(['user_count' => $count]);
            });
    }

    /**
     * 用户
     *
     * @return \Illuminate\Database\Eloquent\Relations\hasMany
     */
    public function user()
    {
        return $this->hasMany(User::class);
    }
}
